package com.ff.javamonkey.test.ui;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ff.javamonkey.R;
import com.ff.javamonkey.bluetooth.BluetoothService;

public class ScreenTestActivity extends Activity {
	// Debugging
	private static final String TAG = "BluetoothTestActivity";
	
	// UIs
	private TextView mTitle;
	private ListView mConversationView;
	private EditText mOutEditText;
	private Button mBrowseButton;
	private Button mSendButton;
	
	// Local Bluetooth Adapter
	private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothService mBtService = null;
	
	// Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    private Object f;
    
    // Message types sent from the BluetoothService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final int MESSAGE_WRITE_FILE = 6;
    public static final int MESSAGE_WRITE_FILE_FINISHED = 7;
    
    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_main);
		
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		
		if (mBluetoothAdapter == null) {
			Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
			finish();
			return;
		}
	}
	
	@Override
	public void onStart() {
		super.onStart();
		Log.i(TAG, "ScreenTestActivity: onStart");
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		}
		else {
			if (mBtService == null) setupService();
		}
	}
	
	@Override
	public synchronized void onResume() {
		super.onResume();
		Log.i(TAG, "ScreenTestActivity: onResume");
		if (mBtService != null) {
			if (mBtService.getState() == BluetoothService.STATE_NONE);
				mBtService.start();
		}
	}
	
	@Override
    public synchronized void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mBtService != null) mBtService.stop();
    }
	
	private void setupService() {
		Log.i(TAG, "setupService baby");
		mBrowseButton = (Button)findViewById(R.id.button_browsefile);
		mBrowseButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
//				Intent i = new Intent(ScreenTestActivity.this, BluetoothConnectActivity.class);
//				startActivityForResult(i, BluetoothConnectActivity.REQUEST_FILEPATH);
				mBtService.writeFile("/sdcard/Cinemator.apk");
			}
		});
		
		mSendButton = (Button)findViewById(R.id.button_send);
		mSendButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
//				if (mBtService.getState() != BluetoothService.STATE_CONNECTED) {
//					Toast.makeText(ScreenTestActivity.this, "Not connected", Toast.LENGTH_SHORT).show();
//					return;
//				}
				if (f != null) {
					mBtService.writeFile(f);
				}
			}
		});
		
		mBtService = new BluetoothService(ScreenTestActivity.this, mHandler);
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE:
			if (resultCode == Activity.RESULT_OK) {
				String address = data.getExtras()
									.getString(DeviceList.EXTRA_DEVICE_ADDRESS);
				Log.i(TAG, "Device to connect: " + address);
				BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
				mBtService.connect(device);
				Log.i(TAG, mBtService.getState() + " state after REQUEST_CONNECT_DEVICE");
			}
		case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                setupService();
            } else {
                finish();
            }
            break;
		case BluetoothConnectActivity.REQUEST_FILEPATH:
			if (data!=null) {
				Bundle bundle = data.getExtras();
				f = bundle.get("file");
				mSendButton.setEnabled(true);
				Log.i(TAG, mBtService.getState() + " state after REQUEST_FILEPATH");
			}
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.option_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.scan:
			Log.i(TAG, "Intent scan clicked");
			Intent serverIntent = new Intent(this, DeviceList.class);
			startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
			return true;
		case R.id.discoverable:
			ensureDiscoverable();
			return true;
		}
		return false;
	}
	
	private void ensureDiscoverable() {
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
	}
	
	// The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                switch (msg.arg1) {
                case BluetoothService.STATE_CONNECTED:
                    mTitle.setText(msg.toString());
//                    mTitle.append(mConnectedDeviceName);
//                    mConversationArrayAdapter.clear();
//                    break;
//                case BluetoothChatServices.STATE_CONNECTING:
//                    mTitle.setText(R.string.title_connecting);
//                    break;
//                case BluetoothChatServices.STATE_LISTEN:
//                case BluetoothChatServices.STATE_NONE:
//                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
//                mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
            case MESSAGE_WRITE_FILE:
//            	progDialog.setMax(msg.arg2);
//            	percent = (int)((msg.arg1*100)/msg.arg2);            	
//            	Log.e(TAG, "numread : " + msg.arg1 + " fileLength : " + msg.arg2 + " Percentage : " + percent);
//            	progDialog.setProgress(msg.arg1);
            	break;
            case MESSAGE_WRITE_FILE_FINISHED:
//            	dismissDialog(PROGRESS_DIALOG);
            	break;	
                
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
//                mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
//                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
//                Toast.makeText(getApplicationContext(), "Connected to "
//                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
}
